import React, { useState, useEffect, useRef } from 'react';

import { Pagination } from '@/components';
import { connect } from 'umi';
import moment from 'moment';
import { Card, DatePicker, Modal, Table, Form, Button } from 'antd';
import { get as _get } from 'object-path';
import { formatMessage } from 'umi';
// import _ from 'lodash';
// import { call } from 'redux-saga/effects';
// import cookie from 'js-cookie';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
// import styles from './List.less';
import { withRoutePage } from '@/utils/enhanceUtils';

const AttendanceDetail = props => {
    const {
        dispatch,
        attendanceMineList,
        attendanceMineList: { pagination },
        loading,
        form: { getFieldDecorator }
    } = props;

    const isFirstRun = useRef(true);
    const user = JSON.parse(localStorage.getItem('user'));
    const [visible, setVisible] = useState(false);
    const [whichMonth, setWhichMonth] = useState(
        _get(props, 'location.query.date') && _get(props, 'location.query.date') !== 'undefined'
            ? moment(_get(props, 'location.query.date')).format('YYYY-MM')
            : moment().format('YYYY-MM')
    );
    const [signDate, setSignDate] = useState('');

    const showModal = () => {
        setVisible(true);
    };

    const seeDetail = async record => {
        const parame = {
            employeeCode: _get(user, 'employeeCode', ''),
            startTime: moment(record.signDate).format('YYYY-MM-DD'),
            endTime: moment(record.signDate).format('YYYY-MM-DD'),
            pageNo: 1,
            pageSize: 50
        };

        await dispatch({
            type: 'attendanceMineList/getmyattendancedetail',
            payload: {
                parame
            }
        });
        setSignDate(record.signDate);
        showModal();
    };

    const columns = [
        {
            title: formatMessage({
                id: 'form.thead.date'
            }),
            dataIndex: 'signDate',
            key: 'signDate'
        },
        {
            title: formatMessage({
                id: 'form.thead.signInTime'
            }),
            dataIndex: 'signInTime',
            key: 'signInTime'
        },
        {
            title: formatMessage({
                id: 'form.thead.signInStatusNick'
            }),
            dataIndex: 'signInStatusNick',
            key: 'signInStatusNick',
            render: text => {
                if (text === '早退' || text === '迟到') {
                    return <span style={{ color: '#007AFF' }}>{text}</span>;
                }
                if (text === '缺卡' || text === '缺勤') {
                    return <span style={{ color: '#F5323E' }}>{text}</span>;
                }
                return text;
            }
        },
        {
            title: formatMessage({
                id: 'form.thead.signOutTime'
            }),
            dataIndex: 'signOutTime',
            key: 'signOutTime'
        },
        {
            title: formatMessage({
                id: 'form.thead.signOutStatusNick'
            }),
            dataIndex: 'signOutStatusNick',
            key: 'signOutStatusNick',
            render: text => {
                if (text === '早退' || text === '迟到') {
                    return <span style={{ color: '#007AFF' }}>{text}</span>;
                }
                if (text === '缺卡' || text === '缺勤') {
                    return <span style={{ color: '#F5323E' }}>{text}</span>;
                }
                return text;
            }
        },
        {
            title: formatMessage({
                id: 'form.thead.action'
            }),
            dataIndex: 'action',
            key: 'action',
            render: (text, record) => <a onClick={() => seeDetail(record)}>查看打卡记录</a>
        }
    ];
    const columnsModal = [
        {
            title: formatMessage({
                id: 'form.thead.userNo'
            }),
            dataIndex: 'userNo',
            key: 'userNo'
        },
        {
            title: formatMessage({
                id: 'form.thead.attDatetime'
            }),
            dataIndex: 'attDatetime',
            key: 'attDatetime'
        },
        {
            title: formatMessage({
                id: 'form.thead.deviceName'
            }),
            dataIndex: 'deviceName',
            key: 'deviceName'
        }
    ];

    const getData = type => {
        console.log(whichMonth, '11111111111111111111111111111');
        const parame = {
            employeeCode: _get(user, 'employeeCode', ''),
            whichMonth,
            pageNo: type ? 1 : pagination.current,
            pageSize: pagination.pageSize
        };
        dispatch({
            type: 'attendanceMineList/getmyattendancerecord',
            payload: {
                parame
            }
        });
    };

    useEffect(() => {
        getData();

        return () => {
            dispatch({
                type: 'attendanceMineList/setPagination',
                pagination: {
                    current: 1,
                    pageSize: 10,
                    total: 0
                }
            });
        };
    }, []);
    const onChange = v => {
        setWhichMonth(v.format('YYYY-MM'));
    };

    // 页码改变
    const changeTable = async newPagination => {
        await dispatch({
            type: 'attendanceMineList/setPagination',
            pagination: {
                ...pagination,
                ...newPagination
            }
        });
    };
    useEffect(() => {
        // 第一次不运行
        if (isFirstRun.current) {
            isFirstRun.current = false;
            return;
        }
        getData();
    }, [pagination.pageSize, pagination.current]);

    const { MonthPicker } = DatePicker;
    const attendancerecord = _get(attendanceMineList, 'attendancerecord', []);
    const attendancedetail = _get(attendanceMineList, 'attendancedetail', []);

    return (
        <PageHeaderWrapper>
            <Card
                bordered={false}
                title="出勤记录"
                extra={
                    <Form layout="inline">
                        <Form.Item
                            label={formatMessage({
                                id: 'stat.name.kqy'
                            })}
                        >
                            {getFieldDecorator('whichMonth', {
                                initialValue: whichMonth ? moment(whichMonth, 'YYYY-MM-DD') : ''
                            })(<MonthPicker onChange={onChange} allowClear={false} />)}
                        </Form.Item>
                        <Form.Item>
                            <Button
                                type="primary"
                                onClick={() => {
                                    getData(true);
                                }}
                            >
                                {formatMessage({
                                    id: 'form.search'
                                })}
                            </Button>
                        </Form.Item>
                    </Form>
                }
            >
                <Table
                    bordered={false}
                    dataSource={attendancerecord}
                    columns={columns}
                    rowKey="id"
                    loading={loading}
                    onChange={changeTable}
                    pagination={false}
                />
                <Pagination {...pagination} onChange={changeTable} loading={loading} />
            </Card>
            <Modal
                title={
                    <div>
                        <div style={{ fontSize: '20px', color: '#333' }}>
                            {formatMessage({
                                id: 'stat.ckdkjl'
                            })}
                        </div>
                        <p
                            style={{
                                color: 'rgba(0, 0, 0, .45)',
                                fontSize: '14px',
                                marginBottom: 0
                            }}
                        >
                            {signDate}
                            {formatMessage({
                                id: 'stat.dksj'
                            })}
                        </p>
                    </div>
                }
                width={600}
                footer={null}
                visible={visible}
                onOk={() => setVisible(false)}
                onCancel={() => setVisible(false)}
                centered
            >
                <Table
                    dataSource={attendancedetail}
                    columns={columnsModal}
                    pagination={false}
                    loading={loading}
                    rowKey="id"
                />
            </Modal>
        </PageHeaderWrapper>
    );
};

export default withRoutePage(
    connect(({ attendanceMineList, loading }) => ({
        attendanceMineList,
        loading: loading.models.attendanceMineList
    }))(Form.create()(AttendanceDetail))
);
